<template>
  <div>
    <div v-if="loaded">
      <fks-row :gutter="15">
        <fks-form
          ref="custom_flow_form"
          :model="customAssigneeEntity"
          label-width="110px"
        >
          <fks-col
            :span="12"
            v-for="item in customAssigneeList"
            :key="item.assignee"
          >
            <fks-form-item
              :required="item.required == '1'"
              :label="item.assigneeLabel"
              :prop="item.assignee"
            >
              <fks-user-selector
                style="width: 102%"
                v-if="item.approvalType !== '4' && item.approvalType !== '5'"
                :readonly="
                  (readonly_flag && item.updatePermission !== '1') ||
                  item.assignee == `${custom_flow_prefix}start` ||
                  item.approvalType == 2 ||
                  (typeof item.sameNodeId == 'string' &&
                    item.sameNodeId.length > 0)
                "
                :username.sync="customAssigneeEntity[item.assignee]"
                :userfullname.sync="
                  customAssigneeEntity[item.assignee + '_fullName']
                "
                :multiple="true"
              ></fks-user-selector>
              <fks-post-selector
                v-else
                :readonly="
                  (readonly_flag && item.updatePermission !== '1') ||
                  item.assignee == `${custom_flow_prefix}start` ||
                  item.approvalType == 4 ||
                  (item.sameNodeId && item.sameNodeId.length > 0)
                "
                :postId.sync="customAssigneeEntity[item.assignee + '_postId']"
                :postName.sync="
                  customAssigneeEntity[item.assignee + '_postName']
                "
                :multiple="true"
              ></fks-post-selector>
            </fks-form-item>
          </fks-col>
        </fks-form>
      </fks-row>
    </div>
    <fks-skeleton style="width: 100%; margin-top: 16px" v-if="!loaded" animated>
      <template #template>
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <fks-skeleton-item variant="text" style="width: 45%" />
          <fks-skeleton-item variant="text" style="width: 45%" />
        </div>
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 16px;
          "
        >
          <fks-skeleton-item variant="text" style="width: 45%" />
          <fks-skeleton-item variant="text" style="width: 45%" />
        </div>
      </template>
    </fks-skeleton>
  </div>
</template>

<script>
import { custom_flow_prefix } from '@/config/app/develop'
import { getCustomNodeDetail, getApprovalList } from './api'
import { getCurrentUser } from './common'
export default {
  name: 'customAssignee',
  props: {
    customAssigneeGroup: {
      type: Object,
      default: () => {
        return {}
      }
    },
    assigneeList: {
      type: Array,
      default: () => {
        return []
      }
    },
    modelKey: {
      type: String,
      default: 'custom_flow_test1'
    },
    validate: {
      // 校验参数
      type: Boolean,
      default: true
    },
    resourceBizId: {
      type: String,
      default: ''
    },
    resourceProcessInstanceId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      custom_flow_prefix: custom_flow_prefix,
      loaded: false,
      readonly_flag: true,
      processInstanceId:
        this.resourceProcessInstanceId ||
        this.$route.query.processInstanceId ||
        '',
      bizId: this.resourceBizId || this.$route.params.bizId || '',
      taskId: this.$route.params.taskId || '',
      customAssigneeList: [],
      customAssigneeEntity: {},
      type: this.$route.params.type, //表单类型
      isPreview: this.$route.path.includes('templatePreview')
      // postName: '',
      // postFullname: ''
    }
  },
  watch: {
    modelKey: {
      handler(val) {
        if (val) {
          this.getApprovalModel(val)
        }
      },
      immediate: true
    },
    customAssigneeEntity: {
      deep: true,
      immediate: true,
      handler: function (val) {
        // 更新与某个节点同步审批人的节点的审批人
        this.customAssigneeList.forEach((item) => {
          if (item.sameNodeId && item.sameNodeId.length > 0) {
            let setSameNode = item.assignee // 设置了相同审批人的节点
            let sameNode = item.sameNodeId // 相同审批人的目标节点
            this.$set(
              val,
              setSameNode,
              val[sameNode] //更新为目标节点的审批人一样
            )
            this.$set(
              val,
              setSameNode + '_fullName',
              val[sameNode + '_fullName'] //更新为目标节点的审批人一样
            )
          }
        })
        // 生成自由流程审批人参数对象
        this.$emit('update:customAssigneeGroup', this.customAssigneeEntity)
        // 生成自由流程审批人所有会签节点数组
        this.customAssigneeList.forEach((item) => {
          if (item.assignee) {
            item.id = !this.customAssigneeEntity[item.assignee + '_id']
              ? null
              : this.customAssigneeEntity[item.assignee + '_id']
            item.assigneeUserName = this.customAssigneeEntity[item.assignee]
            item.assigneeUserFullName = this.customAssigneeEntity[
              item.assignee + '_fullName'
            ]
          }
        })
        this.$emit('update:assigneeList', [...this.customAssigneeList])
      }
    }
  },
  computed: {
    portalId() {
      return this.$store.state.portal.id || ''
    }
  },
  components: {},
  methods: {
    /**
     * @description: 处理流程审批人数组 数据
     * @params : 审批人 array
     */
    handleAssigneeList(array) {
      array.forEach((item, index) => {
        if (item.sameNodeId && item.sameNodeId.length > 0) {
          // 当审批人类型为与某一节点相同审批人时
          let sameNodeId = item.sameNodeId
          let sameNodeIndex = array.findIndex((i) => i.assignee == sameNodeId)
          // approvalType改为相同节点一样
          this.customAssigneeList[index].approvalType = this.customAssigneeList[
            sameNodeIndex
          ].approvalType
          this.$set(
            this.customAssigneeEntity,
            item.assignee,
            array[sameNodeIndex].assigneeUserName //更新为目标节点的审批人一样
          )
          this.$set(
            this.customAssigneeEntity,
            item.assignee + '_fullName',
            array[sameNodeIndex].assigneeUserFullName //更新为目标节点的审批人一样
          )
        } else if (item.approvalType == 1) {
          // 当审批人类型为用户自选时
          let $assignee = ''
          let $assigneeFullname = ''
          // 判断是否为第一个发起节点，如果为发起节点的话则需要将当前登录用户的信息回填到填写人
          if (item.assignee == `${this.custom_flow_prefix}start`) {
            const $currentUser = Object.assign({}, getCurrentUser()) // 获取当前登录人信息的方法（根据实际需要可以进行修改）
            if ($currentUser.userName && $currentUser.userFullname) {
              $assignee = $currentUser.userName
              $assigneeFullname = $currentUser.userFullname
            }
          }
          this.$set(this.customAssigneeEntity, item.assignee, $assignee)
          this.$set(
            this.customAssigneeEntity,
            item.assignee + '_fullName',
            $assigneeFullname
          )
        } else if (item.approvalType == 2) {
          // 当审批人类型为指定人员时，将用户指定的人员赋值到对应的选人组件
          this.$set(
            this.customAssigneeEntity,
            item.assignee,
            item.designationAssigneeUserName //修改指定人员 字段
            //item.assigneeUserName
          )
          this.$set(
            this.customAssigneeEntity,
            item.assignee + '_fullName',
            item.designationAssigneeUserFullName //修改指定人员 字段
            //item.assigneeUserFullName
          )
          // if (item.approvalType == 4) {
          //   // debugger
          //   this.postFullname =
          //     this.type == 'add'
          //       ? item.designationAssigneeUserFullName
          //       : item.assigneeUserFullName
          //   let postNameArr =
          //     this.type == 'add'
          //       ? item.designationAssigneeUserName.split(',')
          //       : item.assigneeUserName.split(',')
          //   postNameArr.forEach((item, index) => {
          //     postNameArr[index] = item.substring(5, item.length)
          //   })
          //   let dealPostName = postNameArr.join(',')
          //   this.postName = dealPostName
          //   this.$forceUpdate()
          // }
        } else if (item.approvalType == 4) {
          if (
            item.designationAssigneeUserFullName &&
            item.designationAssigneeUserName
          ) {
            let assigneeNameArr = item.designationAssigneeUserFullName.split(
              ';'
            )
            let assigneeArr = item.designationAssigneeUserName.split(';')
            this.$set(
              this.customAssigneeEntity,
              item.assignee + '_postId',
              assigneeArr && assigneeArr.length > 0 ? assigneeArr[1] : ''
            )
            this.$set(
              this.customAssigneeEntity,
              item.assignee + '_postName',
              assigneeNameArr && assigneeNameArr.length > 0
                ? assigneeNameArr[1]
                : ''
            )
          } else if (item.assigneeUserName && item.assigneeUserFullName) {
            let assigneeNameArr = item.assigneeUserFullName.split(';')
            let assigneeArr = item.assigneeUserName.split(';')
            this.$set(
              this.customAssigneeEntity,
              item.assignee + '_postId',
              assigneeArr && assigneeArr.length > 0 ? assigneeArr[1] : ''
            )
            this.$set(
              this.customAssigneeEntity,
              item.assignee + '_postName',
              assigneeNameArr && assigneeNameArr.length > 0
                ? assigneeNameArr[1]
                : ''
            )
          }
          this.$set(
            this.customAssigneeEntity,
            item.assignee,
            item.designationAssigneeUserName
          )
          this.$set(
            this.customAssigneeEntity,
            item.assignee + '_fullName',
            item.designationAssigneeUserFullName
          )
        }
      })
      const taskKey = this.$route.params.taskKey
      // 如果为发起节点或者为发起节点则需要将选人只读改为可编辑
      if (this.type === 'add' || taskKey === `${custom_flow_prefix}start`) {
        this.readonly_flag = false
      }
      //显示页面
      this.loaded = true
    },
    /**
     * @description: 获取当前自由流程对应的所有审批节点列表用于渲染审批人
     */
    getApprovalModel() {
      //如果为发起节点,则通过config接口渲染审批人
      if (this.type === 'add') {
        getApprovalList(this.modelKey).then((res) => {
          if (res.status) {
            this.customAssigneeList = [...res.data]
            //处理审批人数组
            this.handleAssigneeList(this.customAssigneeList)
          }
        })
      } else if (this.isPreview) {
        this.readonly_flag = false
        getApprovalList(this.modelKey).then((res) => {
          if (res.status) {
            this.customAssigneeList = [...res.data]
            //处理审批人数组
            this.handleAssigneeList(this.customAssigneeList)
          }
        })
      } else {
        // 如果不为发起节点,则通过detail接口获取审批人参数
        this.setApprovalDetail()
      }
    },
    /**
     * @description: 获取当前执行中流程的审批人详情（如果当前页面为add表单发起页面则不进行获取）
     */
    setApprovalDetail() {
      // this.processInstanceId = this.$route.query.processInstanceId
      if (this.processInstanceId || this.bizId) {
        // 根据processInstanceId或者bizId获取
        const params = {
          processInstanceId: this.processInstanceId,
          bizId: this.bizId
        }
        // 因为detail节点返回字段没有sameNode与updatePermission,所以要请求两个接口互通数据
        getCustomNodeDetail(params).then((res) => {
          if (res.status) {
            this.customAssigneeList = [...res.data]
            if (this.customAssigneeList.length > 0) {
              this.getApprovalList(res)
            } else {
              getApprovalList(this.modelKey).then((res) => {
                if (res.status) {
                  this.customAssigneeList = [...res.data]
                  //处理审批人数组
                  this.handleAssigneeList(this.customAssigneeList)
                  this.getApprovalList(res)
                }
              })
            }
            // this.getApprovalList(res)
          }
        })
      }
    },
    getApprovalList(res) {
      // 获取节点信息，判断是否有节点审批人允许发起后在任意节点变更审批人
      getApprovalList(this.modelKey)
        .then((result) => {
          if (result.status) {
            let arr = [...result.data]
            arr.forEach((item, index) => {
              // 如果某个节点设置为其它节点可编辑，找出这个节点，该节点的审批人改为可编辑，且该节点必须在当前节点之后
              let nowNodeIndex = arr.findIndex(
                (node) => node.assignee == this.$route.params.taskKey
              )
              if (
                item.updatePermission &&
                item.updatePermission == '1' &&
                nowNodeIndex < index
              ) {
                this.$set(
                  this.customAssigneeList[index],
                  'updatePermission',
                  '1'
                )
              }
              // 如果某个节点设置了与其它某个节点相同审批人，找出这个节点，把相同审批人赋值给this.customAssigneeList中
              if (item.sameNodeId && item.sameNodeId.length > 0) {
                // approvalType改为相同节点一样
                let sameNodeIndex = this.customAssigneeList.findIndex(
                  (i) => i.assignee == item.sameNodeId
                )
                this.customAssigneeList[
                  index
                ].approvalType = this.customAssigneeList[
                  sameNodeIndex
                ].approvalType
                this.$set(
                  this.customAssigneeList[index],
                  'sameNodeId',
                  item.sameNodeId
                )
              }
            })
          }
        })
        .then(() => {
          //处理审批人数组
          this.handleAssigneeList(this.customAssigneeList)
          const approvalData = res.data
          approvalData.forEach((item) => {
            this.$set(this.customAssigneeEntity, item.assignee + '_id', item.id)
            this.customAssigneeEntity[item.assignee] = item.assigneeUserName
            this.customAssigneeEntity[item.assignee + '_fullName'] =
              item.assigneeUserFullName
          })
        })
    },
    validateHandler() {
      let validateFlag = false
      this.$refs.custom_flow_form.validate((valid) => {
        if (valid) {
          validateFlag = true
          // this.$emit('update:validate', true)
        }
        // else {
        //   this.$emit('update:validate', false)
        // }
      })
      return validateFlag
    }
  },
  mounted() {
    // this.getApprovalModel()
  }
}
</script>

<style></style>
